package com.heima.admin.globalFilter;

import com.alibaba.fastjson.JSON;
import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


@Component
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //设置哪些路径不拦截
        ArrayList<String> list = new ArrayList<>();
        list.add("login/in");
        list.add("/v2/api-docs");
        //1,获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        for (String url : list) {
            if (path.contains(url)) {
                //放行
                return chain.filter(exchange);
            }
        }
        //2,获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        //3,判断token是否存在
        if (StringUtils.isBlank(token)) {
            //如果不存在就终止
            HashMap<String, Object> map = new HashMap<>();
            map.put("host", request.getRemoteAddress().getHostName());
            map.put("code", HttpStatus.UNAUTHORIZED.value());
            map.put("errorMessage", "需要登录");
            return writeMessage(response, map);
        }
        //4，校验token是否有效
        Claims claimsBody = null;
        try {
            claimsBody = AppJwtUtil.getClaimsBody(token);
            if (claimsBody == null) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("host", request.getRemoteAddress().getHostName());
                map.put("code", HttpStatus.UNAUTHORIZED.value());
                map.put("errorMessage", "解析token失败");
                return writeMessage(response, map);
            }
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i < 1) {
                //5，取出token中的用户id并放入请求头当中
                Object userId = claimsBody.get("id");
                request.mutate().header("userId", String.valueOf(userId));
            }
        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> map2 = new HashMap<>();
            map2.put("host", request.getRemoteAddress().getHostName());
            map2.put("code", HttpStatus.UNAUTHORIZED.value());
            map2.put("errorMessage", "token失效");
            return writeMessage(response, map2);
        }

        //放行
        return chain.filter(exchange);
    }

    /**
     * 返回错误提示信息
     *
     * @param response
     * @param resultMap 响应结果
     * @return
     */
    private Mono<Void> writeMessage(ServerHttpResponse response, Map<String, Object> resultMap) {
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(resultMap));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
